package com.dream.common.thread;

import com.dream.common.task.ThreadTask;
import org.jctools.queues.MpscUnboundedArrayQueue;

import java.util.Queue;

/**
 * @author : ChenYu
 * @Classname : DreamThread
 * @Date : 2021/9/13 上午11:35
 */
public class DreamThread extends Thread implements IThread{

    /**
     * 线程状态
     */
    protected ThreadState state;

    /**
     * 运行中
     */
    protected volatile boolean running;

    /**
     * 等待退出
     */
    protected volatile boolean waitBreak;

    /** 每个数组的长度 */
    private static final int MPSC_CHUNK_SIZE =  1024;

    /**
     * 顺序执行的任务
     */
    private Queue<ThreadTask> lastQueue;

    /**
     * 插队执行的任务
     */
    private Queue<ThreadTask> firstQueue;


    public DreamThread(Queue<ThreadTask> lastQueue, Queue<ThreadTask> firstQueue) {
        this.lastQueue = lastQueue;
        this.firstQueue = firstQueue;
    }

    public DreamThread() {
        this.firstQueue =  new MpscUnboundedArrayQueue<>(MPSC_CHUNK_SIZE);
        this.lastQueue =  new MpscUnboundedArrayQueue<>(MPSC_CHUNK_SIZE);
    }

    @Override
    public synchronized void start() {
        super.start();
    }

    @Override
    public boolean addTask(ThreadTask task) {
        return lastQueue.add(task);
    }

    @Override
    public boolean insertTask(ThreadTask task) {
        return firstQueue.add(task);
    }

    /**
     * 阻塞等待结束线程
     *
     * @return
     */
    @Override
    public boolean close(boolean waitBreak) {
        if (this.running && !this.waitBreak) {
            this.waitBreak = waitBreak;
            if (!waitBreak) {
                this.running = false;
            }

            // 等待线程结束
            state = ThreadState.STATE_CLOSING;
            try {
                join();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 设置状态
            this.running = false;
            this.waitBreak = false;
            this.state = ThreadState.STATE_CLOSED;
        }
        return true;
    }
}
